package com.yjha.lzmarathonsys.controller;

import com.yjha.lzmarathonsys.bean.TbUser;
import com.yjha.lzmarathonsys.dto.Param;
import com.yjha.lzmarathonsys.service.TbUserService;
import com.yjha.lzmarathonsys.utils.JwtUtils;
import com.yjha.lzmarathonsys.utils.PageUtils;
import com.yjha.lzmarathonsys.utils.PasswordUtil;
import com.yjha.lzmarathonsys.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.UUID;

@RestController
@RequestMapping("/lzmarathonsys/tbuser")
@Api(tags = "管理员管理")
public class TbUserController {

    @Autowired
    private TbUserService service;

    @ApiOperation(value = "用户注册", notes = "用户注册")
    @PostMapping("/register")
    public R register(@RequestBody TbUser user) {
        return service.register(user);
    }


    @PostMapping("/list")
    @ApiOperation("管理员列表")
    public R list(@RequestBody TbUser user){
        PageUtils page = service.queryPage(user);

        return R.ok().put("page", page);
    }


    @GetMapping("/delete/{id}")
    @ApiOperation("管理员删除")
    public R delete(@PathVariable("id") Integer id){

        service.removeById(id);

        return R.ok();
    }

    @PostMapping("/update")
    @ApiOperation("管理员修改基本信息")
    public R update(@RequestBody TbUser tbUser){
        TbUser byId = service.getById(tbUser.getId());
        tbUser.setPassword(byId.getPassword());
        tbUser.setSalt(byId.getSalt());
        service.updateById(tbUser);
        return R.ok("修改成功");
    }


    @PostMapping("/updatePassword")
    @ApiOperation("管理员修改密码")
    public R updatePassword(@RequestBody TbUser tbUser){
        TbUser byId = service.getById(tbUser.getId());

        String encryption = PasswordUtil.encryption(tbUser.getOldPassword(), byId.getSalt(), 3);

        if (!encryption.equals(byId.getPassword())){
            return R.ok("旧密码不正确！");
        }

        String salt = UUID.randomUUID().toString();

        byId.setPassword(PasswordUtil.encryption(tbUser.getPassword(),salt,3));
        byId.setSalt(salt);

        service.updateById(byId);

        return R.ok("修改成功！");

    }

    @GetMapping("/getAdminInfo")
    @ApiOperation("获取当前用户信息")
    public R getAdminInfo(HttpServletRequest request){
        String token = JwtUtils.getTokenFromRequest(request);


        String userId = null;
        try {
            userId = String.valueOf(JwtUtils.getUID(token));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        TbUser byId = service.getById(userId);
        byId.setPassword(null);
        byId.setSalt(null);

        return R.ok().put("user", byId);
    }
}
